package cn.gbase.jiangsu.data.transfer.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.BuildingUnit;
import cn.gbase.jiangsu.data.transfer.bean.Community;
import cn.gbase.jiangsu.data.transfer.bean.CommunityBuilding;
import cn.gbase.jiangsu.data.transfer.bean.UnitRoom;
import cn.gbase.jiangsu.data.transfer.common.Constants;
import cn.gbase.jiangsu.data.transfer.dto.AddManyRoomDto;
import cn.gbase.jiangsu.data.transfer.util.CommonUtil;

@IocBean(args = { "refer:dao" })
public class BuildingService extends IdEntityService<UnitRoom> {

	@Inject
	private CommunityService communityService;

	public BuildingService() {
		super();
	}

	public BuildingService(Dao dao) {
		super(dao);
	}

	/**
	 * 根据ID取得楼.
	 * 
	 * @param buildingId
	 *            楼ID
	 * @return
	 */
	public CommunityBuilding getBuilding(int buildingId) {
		return this.dao().fetch(CommunityBuilding.class, buildingId);
	}

	/**
	 * 根据楼号取得楼.
	 * 
	 * @param communityId
	 *            社区ID
	 * @param buildingNo
	 *            楼号
	 * @return
	 */
	public CommunityBuilding getBuildingByNo(int communityId, String buildingNo) {
		return this.dao().fetch(
				CommunityBuilding.class,
				Cnd.where("communityId", "=", communityId).and("buildingNo",
						"=", buildingNo));
	}

	/**
	 * 根据ID取得单元.
	 * 
	 * @param unitId
	 * @return
	 */
	public BuildingUnit getUnit(int unitId) {
		return this.dao().fetch(BuildingUnit.class, unitId);
	}

	/**
	 * 根据单元号取得单元.
	 * 
	 * @param unitId
	 * @return
	 */
	public BuildingUnit getUnitByNo(int buildingId, String unitNo) {
		return this.dao().fetch(
				BuildingUnit.class,
				Cnd.where("buildingId", "=", buildingId).and("unitNo", "=",
						unitNo));
	}

	/**
	 * 根据ID取得房间.
	 * 
	 * @param roomId
	 * @return
	 */
	public UnitRoom getRoom(int roomId) {
		return this.dao().fetch(UnitRoom.class, roomId);
	}

	/**
	 * 取得房间列表.
	 * 
	 * @param pageNumber
	 * @param name
	 * @return
	 */
	public QueryResult getRoomList(int pageNumber, String communityId,
			String buildingNo, String unitNo, String roomNo) {

		if (pageNumber <= 0) {
			pageNumber = 1;
		}

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("1", "=", 1);
		if (communityId != null && communityId.length() > 0) {
			group = group.and("communityId", "=", Integer.valueOf(communityId));
		}
		if (buildingNo != null && buildingNo.length() > 0) {
			group = group.and("buildingNo", "=", buildingNo);
		}
		if (unitNo != null && unitNo.length() > 0) {
			group = group.and("unitNo", "=", unitNo);
		}
		if (roomNo != null && roomNo.length() > 0) {
			group = group.and("roomNo", "=", roomNo);
		}

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber,
				Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao().count(UnitRoom.class, Cnd.where(group));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<UnitRoom>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询
		List<UnitRoom> resultList = this.dao().query(UnitRoom.class,
				Cnd.where(group), pager); // 当前页面显示记录

		// 返回
		return new QueryResult(resultList, pager);
	}

	/**
	 * 根据条件判断房间是否已经存在.
	 * 
	 * @param communityId
	 *            社区ID
	 * @param buildingNo
	 *            楼号
	 * @param unitNo
	 *            单元号
	 * @param roomNo
	 *            房间号
	 * @return
	 */
	public boolean isRoomExist(int communityId, String buildingNo,
			String unitNo, String roomNo) {
		return this.dao().count(
				UnitRoom.class,
				Cnd.where("communityId", "=", communityId)
						.and("buildingNo", "=", buildingNo)
						.and("unitNo", "=", unitNo).and("roomNo", "=", roomNo)) > 0;
	}

	/**
	 * 添加或更新社区.
	 * 
	 * @param Building
	 * @return
	 */
	public boolean addOrUpdRoom(UnitRoom room) {
		if (room.getId() > 0) {
			return updateRoom(room);
		}
		return addRoom(room);
	}

	/**
	 * 添加房间（楼号、单元号不存在时，自动添加）.
	 * 
	 * @param room
	 *            房间
	 * @return
	 */
	public boolean addRoom(UnitRoom room) {

		// 取得或添加楼
		CommunityBuilding building = this.getOrCreateBuilding(
				room.getCommunityId(), room.getBuildingNo());

		// 取得或添加单元
		BuildingUnit unit = this.getOrCreateUnit(building.getId(),
				room.getUnitNo());

		// 插入房间
		room.setUnitId(unit.getId()); // 单元ID
		room.setAddtime(new Date());
		room.setCreateUser(CommonUtil.getLoginUserName());
		room.setRoomCode(CommonUtil.formatRoomNo(room.getRoomNo())); // 房间编码
		this.dao().insert(room);
		return true;
	}

	/**
	 * 取得楼，不存在时则创建.
	 * 
	 * @return
	 */
	private CommunityBuilding getOrCreateBuilding(int communityId,
			String buildingNo) {

		// 取得或添加楼
		CommunityBuilding building = this.getBuildingByNo(communityId,
				buildingNo);
		if (building == null) {
			building = new CommunityBuilding();
			building.setBuildingNo(buildingNo); // 楼号
			building.setBuildingCode(CommonUtil.formatBuildingNo(buildingNo)); // 楼编码
			building.setCommunityId(communityId); // 社区ID
			building.setAddtime(new Date());
			building.setCreateUser(CommonUtil.getLoginUserName());
			building = this.dao().insert(building);
		}
		return building;
	}

	/**
	 * 取得单元，不存在时则创建.
	 * 
	 * @return
	 */
	private BuildingUnit getOrCreateUnit(int buildingId, String unitNo) {

		// 取得或添加单元
		BuildingUnit unit = this.getUnitByNo(buildingId, unitNo);
		if (unit == null) {
			unit = new BuildingUnit();
			unit.setBuildingId(buildingId); // 楼ID
			unit.setUnitNo(unitNo); // 单元号
			unit.setUnitCode(CommonUtil.formatUnitNo(unitNo)); // 单元编码
			unit.setAddtime(new Date());
			unit.setCreateUser(CommonUtil.getLoginUserName());
			unit = this.dao().insert(unit);
		}
		return unit;
	}

	/**
	 * 更新社区.
	 * 
	 * @param Building
	 * @return
	 */
	public boolean updateRoom(UnitRoom room) {
		this.dao().update(room);
		return true;
	}

	/**
	 * 删除社区.
	 * 
	 * @param BuildingId
	 */
	public void deleteRoom(int roomId) {
		this.dao().delete(UnitRoom.class, roomId);

		// 其它关联信息，都要逻辑删除
	}

	/**
	 * 批量添加房间.
	 * 
	 * @param dto
	 */
	public void addManyRoom(AddManyRoomDto dto) {

		// 社区ID
		int commId = dto.getCommunityId();

		// 循环楼号
		int startBuildingNo = Integer.valueOf(dto.getBuildingNoStart());
		int endBuildingNo = Integer.valueOf(dto.getBuildingNoEnd());
		for (int i = startBuildingNo; i <= endBuildingNo; i++) {

			// 取得或添加楼
			CommunityBuilding building = this.getOrCreateBuilding(commId, ""
					+ i);

			// 循环单元号
			int startUnitNo = Integer.valueOf(dto.getUnitNoStart());
			int endUnitNo = Integer.valueOf(dto.getUnitNoEnd());
			for (int j = startUnitNo; j <= endUnitNo; j++) {

				// 取得或添加单元
				BuildingUnit unit = this.getOrCreateUnit(building.getId(), ""
						+ j);

				// 循环楼层号
				int startFloorNo = Integer.valueOf(dto.getFloorNoStart());
				int endFloorNo = Integer.valueOf(dto.getFloorNoEnd());
				for (int k = startFloorNo; k <= endFloorNo; k++) {

					// 循环房间号
					int startRoomNo = Integer.valueOf(dto.getRoomNoStart());
					int endRoomNo = Integer.valueOf(dto.getRoomNoEnd());
					for (int m = startRoomNo; m <= endRoomNo; m++) {

						// 301,1102
						String roomNo = k + CommonUtil.formatRoomNo("" + m);

						// 存在的房间跳过
						if (this.isRoomExist(commId, "" + i, "" + j, roomNo)) {
							continue;
						}

						// 添加房间
						UnitRoom room = new UnitRoom();
						room.setRoomNo(roomNo); // 房间号，如301
						room.setRoomCode(CommonUtil.formatFloorNo("" + k)
								+ CommonUtil.formatRoomNo("" + m)); // 房间编码，如0301
						room.setUnitId(unit.getId()); // 单元ID
						room.setAddtime(new Date());
						room.setCreateUser(CommonUtil.getLoginUserName());
						this.dao().insert(room);
					}
				}
			}
		}
	}

	/**
	 * 生成验证码.
	 * 
	 * @param communityId
	 *            社区ID
	 * @param buildingNo
	 *            楼号
	 * @param unitNo
	 *            单元号
	 * @param roomNo
	 *            房间号
	 * @return
	 */
	public int createCode(String communityId, String buildingNo, String unitNo,
			String roomNo) {

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("1", "=", 1);
		if (communityId != null && communityId.length() > 0) {
			group = group.and("communityId", "=", Integer.valueOf(communityId));
		}
		if (buildingNo != null && buildingNo.length() > 0) {
			group = group.and("buildingNo", "=", buildingNo);
		}
		if (unitNo != null && unitNo.length() > 0) {
			group = group.and("unitNo", "=", unitNo);
		}
		if (roomNo != null && roomNo.length() > 0) {
			group = group.and("roomNo", "=", roomNo);
		}

		// 查询记录总数
		int recordCount = this.dao().count(UnitRoom.class, Cnd.where(group));

		// 没数据，直接返回
		if (recordCount == 0) {
			return 0;
		}

		// 查询
		List<UnitRoom> resultList = this.dao().query(UnitRoom.class,
				Cnd.where(group));

		// 循环更新验证码
		for (UnitRoom room : resultList) {
			String code = this.getRoomFullCode(room);
			String bindCode = CommonUtil.createBindCode(code);
			this.dao().update(UnitRoom.class, Chain.make("bindCode", bindCode),
					Cnd.where("id", "=", room.getId()));
		}

		return resultList.size();

	}

	/**
	 * 得到房间的完整编码，如海逸长洲15号楼2门2801号，假定海逸长洲小区号为1001，则唯一代码为100115022801
	 * 
	 * @param room
	 * @return
	 */
	private String getRoomFullCode(UnitRoom room) {
		BuildingUnit unit = this.getUnit(room.getUnitId());
		CommunityBuilding building = this.getBuilding(unit.getBuildingId());
		Community comm = communityService.getCommunity(building
				.getCommunityId());
		return comm.getCommunityCode() + building.getBuildingCode()
				+ unit.getUnitCode() + room.getRoomCode();
	}

	/**
	 * 取得房间的地址.
	 * 
	 * @param roomId
	 *            房间ID
	 * @return 地址
	 */
	public String getRoomAddress(int roomId) {

		// 房间
		UnitRoom room = this.getRoom(roomId);
		if (room == null) {
			return "";
		}

		// 单元
		BuildingUnit unit = this.getUnit(room.getUnitId());

		// 楼
		CommunityBuilding building = this.getBuilding(unit.getBuildingId());

		// 社区
		Community com = communityService
				.getCommunity(building.getCommunityId());

		// xx小区12-1-202
		return com.getCommunityName() + building.getBuildingNo() + "-"
				+ unit.getUnitNo() + "-" + room.getRoomNo();
	}

	/**
	 * 根据房间ID取得社区.
	 * 
	 * @param roomId
	 *            房间ID
	 * @return 社区
	 */
	public Community getCommunityByRoom(int roomId) {

		// 房间
		UnitRoom room = this.getRoom(roomId);
		if (room == null) {
			return null;
		}

		// 单元
		BuildingUnit unit = this.getUnit(room.getUnitId());

		// 楼
		CommunityBuilding building = this.getBuilding(unit.getBuildingId());

		// 社区
		return communityService.getCommunity(building.getCommunityId());

	}

}
